/**
 * @(#)DateConvertor.java 2011-6-7
 * Copyright 2000-2011 by iampurse@vip.qq.com. All rights reserved.
 */
package com.j3.converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.beanutils.converters.DateTimeConverter;

/**
 * @author qianbiao.wu
 * @date 2011-6-7
 * @version $Revision$
 */
public class MyDateConvertor extends DateTimeConverter {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private DateFormat[] getDateFormats(Locale locale) {
        DateFormat ls = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat ss = new SimpleDateFormat("yyyy-MM-dd");

        DateFormat dt1 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, locale);
        DateFormat dt2 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale);
        DateFormat dt3 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);

        DateFormat d1 = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        DateFormat d2 = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
        DateFormat d3 = DateFormat.getDateInstance(DateFormat.LONG, locale);

        DateFormat rfc3399 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

        return new DateFormat[] { ls, ss, dt1, dt2, dt3, rfc3399, d1, d2, d3 };
    }

    public MyDateConvertor(Object defaultValue) {
        super(defaultValue);
    }

    /**
     * 
     */
    public MyDateConvertor() {
    }

    /* (non-Javadoc)
     * @see org.apache.commons.beanutils.converters.AbstractConverter#getDefaultType()
     */
    @Override
    protected Class<?> getDefaultType() {
        return Date.class;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected Object convertToType(Class targetType, Object value) throws Exception {
        if (value instanceof String) {
            Date result = null;
            DateFormat[] dfs = getDateFormats(Locale.getDefault());
            for (DateFormat df1 : dfs) {
                try {
                    result = df1.parse(value.toString());
                    if (result != null) {
                        break;
                    }
                }
                catch (ParseException ignore) {
                }
            }
            return result;
        }

        return super.convertToType(targetType, value);
    }

    @Override
    protected String convertToString(Object value) throws Throwable {
        return sdf.format((Date) value);
    }

}
